package com.ocom.company.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.ocom.common.constant.MapKey;
import com.ocom.common.dto.CompanyInfoDto;
import com.ocom.common.entity.master.*;
import com.ocom.common.enums.DataSourceEnum;
import com.ocom.common.enums.MasterSlaveEnum;
import com.ocom.common.pojo.company.CompanyListPojo;
import com.ocom.common.request.company.GetCompanySummaryRequest;
import com.ocom.common.utils.StringUtils;
import com.ocom.common.vo.CompanyListInfoVo;
import com.ocom.common.vo.company.ComStatusCountVo;
import com.ocom.company.dao.IDaoCompanyListInfo;
import com.ocom.company.dao.IDaoMngUserInfo;
import com.ocom.company.service.*;
import com.ocom.mysql.aspect.DataSourceAspect;
import com.ocom.redis.aspect.CacheRedisAspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;



@Service
public class CompanyListInfoServiceImpl extends ServiceImpl<IDaoCompanyListInfo, EntityCompanyList> implements CompanyListInfoService {

    private final Logger log = LoggerFactory.getLogger(CompanyListInfoServiceImpl.class);

    @Autowired
    CompanyInfoService companyInfoService;

    @Autowired
    WechatPerInfoService wechatPerInfoService;
    @Autowired
    MngUserInfoService mngUserInfoService;

    @Autowired
    IDaoCompanyListInfo iDaoCompanyListInfo;

    @Autowired
    IDaoMngUserInfo iDaoMngUserInfo;

    @Autowired
    CompanyRoleService companyRoleService;

    //注入CompanyList持久层
    @Autowired
    private IDaoCompanyListInfo daoCompanyListInfo;

    @DataSourceAspect(type= DataSourceEnum.MAIN_DB,isMaster = MasterSlaveEnum.SLAVE)
    @Override
    public EntityCompanyList GetCompanyListInfo(Long companyId){
        return  this.getById(companyId);
    }


    @DataSourceAspect(type= DataSourceEnum.MAIN_DB,isMaster = MasterSlaveEnum.SLAVE)
    @Override
    public List<EntityCompanyList> GetCompanyListInfo(CompanyListInfoVo companyListInfoVo) {
        log.info(" 获取单位列表  参数67【{}】 ",companyListInfoVo);

        //根据传参判断是否为空求出 entityCompanyLists
        QueryWrapper<EntityCompanyList> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotNull(companyListInfoVo.getComId())){
            wrapper.eq("com_id", companyListInfoVo.getComId());
        }

        if (StringUtils.isNotNull(companyListInfoVo.getAgentId())){
            wrapper.eq("agent_id", companyListInfoVo.getAgentId());
        }

        if (StringUtils.isNotEmpty(companyListInfoVo.getComName())){
            wrapper.like("com_name", companyListInfoVo.getComName());
        }
        if (StringUtils.isNotEmpty(companyListInfoVo.getProvince())){
            wrapper.eq("province", companyListInfoVo.getProvince());
        }
        if (StringUtils.isNotEmpty(companyListInfoVo.getCity())){
            wrapper.eq("city", companyListInfoVo.getCity());
        }
        if (companyListInfoVo.getOnly()==1){
            wrapper.eq("is_agent", 1);
        }
        if (companyListInfoVo.getOnly()==2){
            wrapper.eq("is_agent", 0);
        }

        if(companyListInfoVo.getPage()==-1 && companyListInfoVo.getSize()==-1){
            companyListInfoVo.setPage(1);
            companyListInfoVo.setSize(500);
        }
        PageHelper.startPage(companyListInfoVo.getPage(), companyListInfoVo.getSize());

        return  this.list(wrapper);
    }


    /**
     * 添加总库单位列表信息
     * */
    @DataSourceAspect(type= DataSourceEnum.MAIN_DB,isMaster = MasterSlaveEnum.MASTER)
    @Transactional
    @Override
    public Map<String,Object> AddCompanyListInfo(CompanyInfoDto companyInfo) {
        //先执行分库，成功则进入下一步，否则返回错误信息（操作失败：原因（2009））
        EntityCompanyList info = new EntityCompanyList();
        if (StringUtils.isNotNull(companyInfo.getComId())) {
            info.setComId(companyInfo.getComId());
        }
        if (StringUtils.isNotEmpty(companyInfo.getComName())){
            info.setComName(companyInfo.getComName());
        }
        if (StringUtils.isNotNull(companyInfo.getIsAgent())){
            info.setIsAgent(Long.valueOf(companyInfo.getIsAgent()));
        }
        if (StringUtils.isNotNull(companyInfo.getAgentId())){
            info.setAgentId(companyInfo.getAgentId());
        }
        if (StringUtils.isNotNull(companyInfo.getComType())){
            info.setComType(Long.valueOf(companyInfo.getComType()));
        }
        if (StringUtils.isNotNull(companyInfo.getComStatus())){
            info.setComStatus(Long.valueOf(companyInfo.getComStatus()));

        }
        if (StringUtils.isNotEmpty(companyInfo.getProvince())){
            info.setProvince(companyInfo.getProvince());
        }
        if (StringUtils.isNotEmpty(companyInfo.getCity())){
            info.setCity(companyInfo.getCity());
        }
        if (StringUtils.isNotEmpty(companyInfo.getColor())){
            info.setColor(companyInfo.getColor());
        }
    //    info.setSaasNo(companyInfo.getXfStatus()!=null && companyInfo.getXfStatus()==0?"1":"2");
        info.setSaasNo("1");

        info.setCreateUserid(companyInfo.getCreateUserid());
        if (companyInfo.getIsSale() !=null){
            info.setSaasId(companyInfo.getSaasId());
        }
        if (companyInfo.getIsSale() !=null){
            info.setXfStatus(companyInfo.getIsSale());
        }
        if (companyInfo.getIsAccess() !=null){
            info.setMjStatus(companyInfo.getIsAccess());
        }
        daoCompanyListInfo.insert(info);
        Map<String, Object> map = new HashMap<>();
        MapKey mapKey = new MapKey();

        map.put(mapKey.getKey_comId(),info.getComId());
        map.put(mapKey.getKey_comName(),info.getComName());
        map.put(mapKey.getKey_color(),info.getColor());
        return map;
    }

    /**
     * 更新总库单位信息
     * */
    @DataSourceAspect(type= DataSourceEnum.MAIN_DB,isMaster = MasterSlaveEnum.MASTER)
    @Transactional
    @Override
    public Map<String, Object> UpdateCompanyListInfo(CompanyInfoDto companyInfo) {
        //根据company_info.com_id执行总库
        UpdateWrapper<EntityCompanyList> companyInfoQueryWrapper = Wrappers.update();

        companyInfoQueryWrapper.eq("com_id", companyInfo.getComId());

        if (StringUtils.isNotEmpty(companyInfo.getComName())) {
            companyInfoQueryWrapper.set("com_name",companyInfo.getComName());
        }
        if (StringUtils.isNotNull(companyInfo.getIsAgent())) {
            companyInfoQueryWrapper.set("is_agent",Long.valueOf(companyInfo.getIsAgent()));
        }
        if (StringUtils.isNotNull(companyInfo.getAgentId())) {
            companyInfoQueryWrapper.set("agent_id",companyInfo.getAgentId());
        }
        if (StringUtils.isNotNull(companyInfo.getComType())) {
            companyInfoQueryWrapper.set("com_type",Long.valueOf(companyInfo.getComType()));
        }
        if (StringUtils.isNotNull(companyInfo.getComStatus())) {
            companyInfoQueryWrapper.set("com_status",Long.valueOf(companyInfo.getComStatus()));
        }
        if (StringUtils.isNotEmpty(companyInfo.getProvince())) {
            companyInfoQueryWrapper.set("province",companyInfo.getProvince());
        }
        if (StringUtils.isNotEmpty(companyInfo.getCity())) {
            companyInfoQueryWrapper.set("city",companyInfo.getCity());
        }
        if (StringUtils.isNotEmpty(companyInfo.getDistrict())) {
            companyInfoQueryWrapper.set("district",companyInfo.getDistrict());
        }
        if (StringUtils.isNotEmpty(companyInfo.getContPerson())) {
            companyInfoQueryWrapper.set("cont_person",companyInfo.getContPerson());
        }
        if (StringUtils.isNotEmpty(companyInfo.getContPhone())) {
            companyInfoQueryWrapper.set("cont_phone",companyInfo.getContPhone());
        }
        if (StringUtils.isNotEmpty(companyInfo.getContEmail())) {
            companyInfoQueryWrapper.set("cont_email",companyInfo.getContEmail());
        }
        if (StringUtils.isNotEmpty(companyInfo.getContAddress())) {
            companyInfoQueryWrapper.set("cont_address",companyInfo.getContAddress());
        }
        if (StringUtils.isNotEmpty(companyInfo.getRemark())) {
            companyInfoQueryWrapper.set("remark",companyInfo.getRemark());
        }
        /*if (StringUtils.isNotNull(companyInfo.getMjStatus())) {
            companyInfoQueryWrapper.set("mj_status",companyInfo.getMjStatus());
        }
        if (StringUtils.isNotNull(companyInfo.getXfStatus())) {
            companyInfoQueryWrapper.set("xf_status",companyInfo.getXfStatus());
        }*/
        if (StringUtils.isNotNull(companyInfo.getEndTime())) {
            companyInfoQueryWrapper.set("end_time",companyInfo.getEndTime());
        }
        if (StringUtils.isNotNull(companyInfo.getCreateUserid())) {
            companyInfoQueryWrapper.set("create_userid",companyInfo.getCreateUserid());
        }
        if (StringUtils.isNotNull(companyInfo.getColor())) {
            companyInfoQueryWrapper.set("color",companyInfo.getColor());
        }
        if (StringUtils.isNotNull(companyInfo.getCommType())) {
            companyInfoQueryWrapper.set("comm_type",companyInfo.getCommType());
        }
        if (StringUtils.isNotNull(companyInfo.getCommNums())) {
            companyInfoQueryWrapper.set("comm_nums",companyInfo.getCommNums());
        }
        if (StringUtils.isNotNull(companyInfo.getLogoUrl())) {
            companyInfoQueryWrapper.set("logo_url",companyInfo.getLogoUrl());
        }
        if (companyInfo.getIsSale() !=null){
            companyInfoQueryWrapper.set("saas_id",companyInfo.getSaasId());
        }
        if (companyInfo.getIsSale() !=null){
            companyInfoQueryWrapper.set("xf_status",companyInfo.getIsSale());
        }
        if (companyInfo.getIsAccess() !=null){
            companyInfoQueryWrapper.set("mj_status",companyInfo.getIsAccess());
        }
        companyInfoQueryWrapper.set("update_time",new Date());
        this.update(companyInfoQueryWrapper);
        EntityCompanyList entityCompanyList = daoCompanyListInfo.selectOne(companyInfoQueryWrapper);
        Map<String, Object> map = new HashMap<>();
        MapKey mapKey = new MapKey();

        map.put(mapKey.getKey_comId(), entityCompanyList.getComId());
        map.put(mapKey.getKey_comName(), entityCompanyList.getComName());
        map.put(mapKey.getKey_color(), entityCompanyList.getColor());
        return map;
    }


    @DataSourceAspect(type= DataSourceEnum.MAIN_DB,isMaster = MasterSlaveEnum.SLAVE)
    @Override
    public List<CompanyListPojo> getCompanyList(List<Long> ids) {
        List<EntityCompanyList> list= this.listByIds(ids);
        List<CompanyListPojo> companyListPojoList=new ArrayList<>();
        if(list==null || list.size()<=0){
            return companyListPojoList;
        }
        for (EntityCompanyList companyList:list){
            CompanyListPojo companyListPojo=new CompanyListPojo();
            companyListPojo.setCompanyId(companyList.getComId());
            companyListPojo.setCompanyName(companyList.getComName());
            companyListPojo.setColorNo(companyList.getColor());

            QueryWrapper<EntityMjDeviceList> entityMjDeviceListQueryWrapper=new QueryWrapper<>();
            entityMjDeviceListQueryWrapper.eq("com_id",companyList.getComId());

            QueryWrapper<EntityMngUserInfo> entityMngUserInfoQueryWrapper=new QueryWrapper<>();
            entityMngUserInfoQueryWrapper.eq("com_id",companyList.getComId());

            companyListPojo.setUserNumber(iDaoMngUserInfo.selectCount(entityMngUserInfoQueryWrapper));
            companyListPojo.setPId(companyList.getCreateUserid());
            companyListPojo.setEndDate(companyList.getEndTime());

            companyListPojoList.add(companyListPojo);
        }
        return companyListPojoList;
    }

    @Override
    @DataSourceAspect(type= DataSourceEnum.MAIN_DB,isMaster = MasterSlaveEnum.SLAVE)
    public List<CompanyListPojo> getCompanyList(String openid) {
        List<CompanyListPojo> companyListPojoList=new ArrayList<>();

        QueryWrapper<EntityWechatPerInfo> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("openid",openid);
        queryWrapper.gt("p_id",0);
        List<EntityWechatPerInfo>  list = wechatPerInfoService.list(queryWrapper);
        List<Long> comIds =new ArrayList<>();
        if(!list.isEmpty() && list.size()>0){
            comIds = list.stream().map(EntityWechatPerInfo -> EntityWechatPerInfo.getComId()).collect(Collectors.toList());
        }else{
            return companyListPojoList;
        }

        //查找单位

        List<EntityCompanyList> list1= this.listByIds(comIds);

        if(list1==null || list1.size()==0){
            return companyListPojoList;
        }

        //查找管理员
        List<Long>  ids =  list.stream().map(EntityWechatPerInfo -> EntityWechatPerInfo.getPId()).collect(Collectors.toList());
        List<EntityMngUserInfo> userInfoList = mngUserInfoService.getMngUserList(ids);
        if(userInfoList==null || userInfoList.size()==0){
            return companyListPojoList;
        }
//        List<Long> pIds = userInfoList.stream().map(EntityMngUserInfo -> EntityMngUserInfo.getId()).collect(Collectors.toList());


        comIds = list.stream().map(EntityCompanyList -> EntityCompanyList.getComId()).collect(Collectors.toList());

        for (EntityMngUserInfo mngUserInfo:userInfoList){
            if(!comIds.contains(mngUserInfo.getComId())){
                continue;
            }
            CompanyListPojo companyListPojo=new CompanyListPojo();


            companyListPojo.setUserName(mngUserInfo.getUserName());
            companyListPojo.setPId(mngUserInfo.getId());
            companyListPojo.setRole(mngUserInfo.getRole());
            companyListPojo.setDeptId(mngUserInfo.getDeptId());
            companyListPojo.setAreaId(mngUserInfo.getAreaId());
            if(mngUserInfo.getRole()==41l){
                companyListPojo.setMerchId(mngUserInfo.getBnsId());
            }
            companyListPojo.setCompanyId(mngUserInfo.getComId());
            if(mngUserInfo.getRole() > 10000L){
                EntityCompanyRole entityCompanyRole = this.companyRoleService.getComRole(mngUserInfo.getComId(),mngUserInfo.getRole());
                if(ObjectUtil.isNotEmpty(entityCompanyRole)){
                    companyListPojo.setParentRole(entityCompanyRole.getParentRole().longValue());
                    companyListPojo.setRoleName(entityCompanyRole.getRoleName());
                }
            }
            for (EntityCompanyList companyList:list1){
                if(!companyList.getComId().equals(mngUserInfo.getComId())) continue;
                companyListPojo.setEndDate(companyList.getEndTime());
                companyListPojo.setCompanyName(companyList.getComName());
                companyListPojo.setColorNo(companyList.getColor());
                break;
            }
            companyListPojoList.add(companyListPojo);
        }


//        Map<Long,Long> UserPid=new HashMap<>();
//        for (EntityWechatPerInfo entityWechatPerInfo:list){
//            UserPid.put(entityWechatPerInfo.getComId(),entityWechatPerInfo.getPId());
//        }
//        for (EntityCompanyList companyList:list1){
//            CompanyListPojo companyListPojo=new CompanyListPojo();
//            companyListPojo.setCompanyId(companyList.getComId());
//            companyListPojo.setCompanyName(companyList.getComName());
//            companyListPojo.setColorNo(companyList.getColor());
//
//            QueryWrapper<EntityMjDeviceList> entityMjDeviceListQueryWrapper=new QueryWrapper<>();
//            entityMjDeviceListQueryWrapper.eq("com_id",companyList.getComId());
//
//            QueryWrapper<EntityMngUserInfo> entityMngUserInfoQueryWrapper=new QueryWrapper<>();
//            entityMngUserInfoQueryWrapper.eq("com_id",companyList.getComId());
//
//            companyListPojo.setUserNumber(iDaoMngUserInfo.selectCount(entityMngUserInfoQueryWrapper));
//
//            if(UserPid.containsKey(companyList.getComId())){
//                companyListPojo.setPId(UserPid.get(companyList.getComId()));
//            }else{
//                continue;
//            }
//
//            companyListPojo.setEndDate(companyList.getEndTime());
//            companyListPojoList.add(companyListPojo);
//        }
        return companyListPojoList;
    }

    @DataSourceAspect(type= DataSourceEnum.MAIN_DB,isMaster = MasterSlaveEnum.SLAVE)
    @Override
    public EntityCompanyList getCompanyList(Long comId) {
        QueryWrapper<EntityCompanyList> query = Wrappers.query();
        query.eq("com_id",comId);
        query.last("limit 1");
        return daoCompanyListInfo.selectOne(query);
    }


    /**
     * 是否存在企业名
     * @param companyName
     * @return
     */
    @Override
    @DataSourceAspect(type= DataSourceEnum.MAIN_DB,isMaster = MasterSlaveEnum.SLAVE)
    public boolean isExistName(String companyName){
        QueryWrapper<EntityCompanyList> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("com_name",companyName);
        Integer count=this.count(queryWrapper);
        return count>0?true:false;
    }

    @DataSourceAspect(type= DataSourceEnum.MAIN_DB,isMaster = MasterSlaveEnum.MASTER)
    @Override
    public void modifyColor(Long companyId, String colorNo) {
        UpdateWrapper<EntityCompanyList> updateWrapper=new UpdateWrapper<>();
        updateWrapper.eq("com_id",companyId);
        updateWrapper.set("color",colorNo);
        this.update(updateWrapper);
    }

    @DataSourceAspect(type= DataSourceEnum.MAIN_DB,isMaster = MasterSlaveEnum.MASTER)
    @Override
    public void modifyName(Long companyId, String companyName) {
        UpdateWrapper<EntityCompanyList> updateWrapper=new UpdateWrapper<>();
        updateWrapper.eq("com_id",companyId);
        updateWrapper.set("com_name",companyName);
        this.update(updateWrapper);
    }



    @DataSourceAspect(type= DataSourceEnum.MAIN_DB,isMaster = MasterSlaveEnum.MASTER)
    @Override
    public void modifyPid(Long companyId, Long pId) {
        UpdateWrapper<EntityCompanyList> updateWrapper=new UpdateWrapper<>();
        updateWrapper.eq("com_id",companyId);
        updateWrapper.set("create_userid",pId);
        this.update(updateWrapper);
    }

    @Override
    @DataSourceAspect(type= DataSourceEnum.MAIN_DB,isMaster = MasterSlaveEnum.SLAVE)
    @CacheRedisAspect(prefix = ":getCompanyListByAgentId",element = {"agentId"} ,deadline = 60l)
    public List<EntityCompanyList> getCompanyListByAgentId(Long agentId) {
        QueryWrapper<EntityCompanyList> queryWrapper=new QueryWrapper<>();
        queryWrapper.select("com_id","com_name");
        if(agentId!=null && agentId>1){
            queryWrapper.eq("com_id",agentId);
            queryWrapper.or().eq("agent_id",agentId);
        }
        return this.list(queryWrapper);
    }

    @Override
    @DataSourceAspect(type= DataSourceEnum.MAIN_DB,isMaster = MasterSlaveEnum.SLAVE)
    public List<EntityCompanyList> getAgents() {
        QueryWrapper<EntityCompanyList> queryWrapper=new QueryWrapper<>();
        queryWrapper.select("com_id","com_name");
        queryWrapper.eq("is_agent", 1);
        return this.list(queryWrapper);
    }

    @DataSourceAspect(type= DataSourceEnum.MAIN_DB,isMaster = MasterSlaveEnum.SLAVE)
    @Override
    public List<EntityCompanyList> getCompanySummary(GetCompanySummaryRequest getCompanySummaryRequest) {
        PageHelper.startPage(getCompanySummaryRequest.getPage(), getCompanySummaryRequest.getSize());
        QueryWrapper<EntityCompanyList> queryWrapper=new QueryWrapper<>();
        if(getCompanySummaryRequest.getOnlyCom()==1){
            queryWrapper.eq("is_agent",0);
        }else {
            //如果@comId==0 and @saasNo==0 and @xfVer==0 and @mjVer==0 and @subDb==0 and @comName==’’ and @province==’’：
            if (getCompanySummaryRequest.getComId() == 0 && getCompanySummaryRequest.getSaasNo() == 0 && getCompanySummaryRequest.getXfVer() == 0
                    && getCompanySummaryRequest.getMjVer() == 0 && getCompanySummaryRequest.getSubDb() == 0 && StringUtils.isEmpty(getCompanySummaryRequest.getComName())
                    && StringUtils.isEmpty(getCompanySummaryRequest.getProvince())) {
                if (getCompanySummaryRequest.getAgentId() == 0) {
                    queryWrapper.and(wrapper -> wrapper.eq("is_agent", 1).or().eq("com_id", 1));
                } else {
                    queryWrapper.and(wrapper -> wrapper.eq("is_agent", getCompanySummaryRequest.getAgentId()).or().eq("com_id", getCompanySummaryRequest.getComId()));
                }
            } else {
                queryWrapper.eq("is_agent", 0);
            }
        }
        //
        if (getCompanySummaryRequest.getComStatus()>0){
            queryWrapper.eq("com_status",getCompanySummaryRequest.getComStatus());
        }
        if (getCompanySummaryRequest.getAgentId()>0){
            queryWrapper.eq("agent_id",getCompanySummaryRequest.getAgentId());
        }
        if (getCompanySummaryRequest.getComId()>0){
            queryWrapper.eq("com_id",getCompanySummaryRequest.getComId());
        }
        if (getCompanySummaryRequest.getSaasNo()>0){
            queryWrapper.eq("saas_id",getCompanySummaryRequest.getSaasNo());
        }
        if (getCompanySummaryRequest.getXfVer()>0){
            queryWrapper.eq("xf_status",getCompanySummaryRequest.getXfVer());
        }
        if (getCompanySummaryRequest.getMjVer()>0){
            queryWrapper.eq("mj_status",getCompanySummaryRequest.getMjVer());
        }
        if (StringUtils.isNotEmpty(getCompanySummaryRequest.getComName())){
            queryWrapper.like("com_name",getCompanySummaryRequest.getComName());
        }
        if (StringUtils.isNotEmpty(getCompanySummaryRequest.getProvince())){
            queryWrapper.like("province",getCompanySummaryRequest.getProvince());
        }
        if (getCompanySummaryRequest.getSubDb()==1){
            queryWrapper.le("com_id",500);
        }
        if (getCompanySummaryRequest.getSubDb()==2){
            queryWrapper.gt("com_id",500);
        }
        return this.list(queryWrapper);
    }

    @Override
    @DataSourceAspect(type= DataSourceEnum.MAIN_DB,isMaster = MasterSlaveEnum.MASTER)
    public Boolean updateCompanyListById(EntityCompanyList entityCompanyList) {
        return this.updateById(entityCompanyList);
    }

    @Override
    @DataSourceAspect(type= DataSourceEnum.MAIN_DB,isMaster = MasterSlaveEnum.SLAVE)
    public List<ComStatusCountVo> getCompanyList(Long beginComId, Long endComId) {
        return iDaoCompanyListInfo.selectComStatusCount(beginComId,endComId);
    }

}
